package orchestration.conditions.jexlImpl;

import java.util.Collection;

import orchestration.businessprocess.execution.Property;
import orchestration.conditions.IConditionEvaluator;
import orchestration.conditions.exceptions.CheckingConditionException;

import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;

/**
 * An {@link IConditionEvaluator} that uses the Java EXpression Language
 * library (from Apache) to evaluate conditions
 * @author <a href="mailto:car.ferrarini@gmail.com">Carlo Ferrarini</a>
 *
 */
public class JexlAdapter implements IConditionEvaluator {

	@Override
	public boolean check(String expression,
			Collection<Property> collection)
			throws CheckingConditionException {
		boolean result=false;

		JexlEngine jexl = new JexlEngine();
		JexlContext jc = getMapContext(collection);
		try {
			Expression expr = jexl.createExpression( expression );
			Object o = expr.evaluate(jc);
			result= ((Boolean)o).booleanValue();
		} catch (Exception e) {
			throw new CheckingConditionException(e.getMessage());
		}
		return result;
	}

	private JexlContext getMapContext(
			Collection<Property> collection) {
		JexlContext jc= new MapContext();
		for(Property prop : collection){
			jc.set(prop.getName(), prop.getValue());
		}
		return jc;
	}

}
